const roleService = require('../services/roleService');
const { success, successWithData, error } = require('../utils/resultwrapper');

class RoleController {
  // 获取角色列表
  async getRoleList(req, res) {
    try {
      const { pageNum = 1, pageSize = 10, keywords, status } = req.query;
      const result = await roleService.getRoleList({ page: parseInt(pageNum), size: parseInt(pageSize), keywords, status });
      res.json(successWithData(result));
    } catch (err) {
      res.json(error(err.message));
    }
  }

  // 获取角色详情
  async getRoleById(req, res) {
    try {
      const { id } = req.params;
      const role = await roleService.getRoleById(id);
      res.json(successWithData(role));
    } catch (err) {
      res.json(error(err.message));
    }
  }

  // 创建角色
  async createRole(req, res) {
    try {
      const roleData = req.body;
      const result = await roleService.createRole(roleData);
      res.json(successWithData(result));
    } catch (err) {
      res.json(error(err.message));
    }
  }

  // 更新角色
  async updateRole(req, res) {
    try {
      const { id } = req.params;
      const roleData = req.body;
      const result = await roleService.updateRole(id, roleData);
      res.json(successWithData(result));
    } catch (err) {
      res.json(error(err.message));
    }
  }

  // 删除角色
  async deleteRoles(req, res) {
    try {
      const { ids } = req.params;
      const idArray = ids.split(',');
      await roleService.deleteRoles(idArray);
      res.json(success());
    } catch (err) {
      res.json(error(err.message));
    }
  }

  // 分配角色菜单
  async assignRoleMenus(req, res) {
    try {
      const { roleId } = req.params;
      const { menuIds } = req.body;
      await roleService.assignRoleMenus(roleId, menuIds);
      res.json(success());
    } catch (err) {
      res.json(error(err.message));
    }
  }

  // 获取角色菜单
  async getRoleMenuIds(req, res) {
    try {
      const { roleId } = req.params;
      const menus = await roleService.getRoleMenuIds(roleId);
      res.json(successWithData(menus));
    } catch (err) {
      res.json(error(err.message));
    }
  }

  // 获取角色下拉数据
  async getRoleOptions(req, res) {
    try {
      const options = await roleService.getRoleOptions();
      res.json(successWithData(options));
    } catch (err) {
      res.json(error(err.message));
    }
  }
}

module.exports = new RoleController();